import { subscribeWithSelector } from 'zustand/middleware'
import { t } from 'i18next'
import create from 'zustand'
import { UserEntity } from '@/api/create/interface'
import { fetchGetPollPlanList } from '@/api/create/poll'
import { useCreateContentStore } from '../../store'
import { PollMtEntity } from './interface'
import Alert from '@/components/Alert'

type StateStore = {
	/**是否开启预案 */
	enablePoll: boolean
	/** 预案id */
	id: string
	/** 自定义轮询间隔 */
	interval: number | undefined
	/** 轮询间隔 */
	intervalType: string
	memberList: Array<UserEntity>
	name: string
	/** 是否发言人 */
	isSpeaker: boolean
	num: number | undefined
	/** 轮询间隔是否不限次数 */
	isPollTimesLimit: boolean
	/** 预案列表 */
	pollPlanList: Array<{
		label: string
		value: string
	}>
}

type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	init: (d: PollMtEntity | null) => void

	loadPlanData: () => void
	getPollData: (repeat?: boolean) => PollMtEntity | undefined
	checkData: () => boolean
}

const initialState: StateStore = {
	enablePoll: false,
	id: '',
	interval: 0,
	intervalType: '30',
	memberList: [],
	name: '',
	num: undefined,
	isSpeaker: false,
	isPollTimesLimit: true,
	pollPlanList: [{ label: t('不使用预案'), value: '0' }],
}

export const useMeetingPollStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		init: (data) => {
			if (data && data.mode && data.mode !== 0) {
				set({
					enablePoll: true,
					id: data.id ?? '',
					interval: data.keep_time ?? 5,
					intervalType: [15, 30, 60].indexOf(data.keep_time) !== -1 ? String(data.keep_time) : '0',
					memberList: data.members ?? [],
					name: data.name ?? '',
					num: data.num ? data.num : undefined,
					isSpeaker: data.mode === 3,
					isPollTimesLimit: data.num === 0,
					pollPlanList: [{ label: t('不使用预案'), value: '0' }],
				})
			} else {
				set(initialState)
			}
			get().loadPlanData()
		},
		/**加载预案 */
		loadPlanData: () => {
			const { preKey, isTemplate } = useCreateContentStore.getState()
			const url = `${isTemplate ? '/personal_templates' : '/meetings'}/${preKey}/prepolls?count=0`
			fetchGetPollPlanList(url).then((res) => {
				if (res.success && res.data) {
					const pollData = res.data
					let arr = pollData ? pollData.map((item) => ({ label: item.name, value: item.id })) : []
					arr.unshift({ label: t('不使用预案'), value: '0' })
					set({ pollPlanList: arr })
				}
			})
		},
		getPollData: (repeat) => {
			const { isSpeaker, interval, memberList, num, intervalType, name, enablePoll, pollPlanList } = get()
			if (!enablePoll) {
				return undefined
			}
			const planValue = pollPlanList.find((item) => item.label === name)?.value ?? '0'
			let _memberList = memberList.map((value) => {
				return Object.assign({}, value, { conf_e164: value['conf_e164'] || value['parent_id'] })
			})
			return {
				id: '',
				mode: isSpeaker ? 3 : 1,
				keep_time: intervalType !== '0' ? Number(intervalType) : interval ?? 0,
				members: _memberList,
				name: repeat ? '' : planValue === '0' ? '' : name,
				num: num ?? 0,
			}
		},
		checkData: () => {
			const { enablePoll, intervalType, interval, isPollTimesLimit, num } = get()
			if (!enablePoll) return true
			let flag = true
			if (intervalType === '0') {
				if (interval === undefined) {
					Alert(t('请设置轮询间隔'))
					return false
				} else if (interval < 5 || interval > 7200) {
					Alert(t('轮询间隔范围：5s~7200s'))
					return false
				}
			}
			if (!isPollTimesLimit) {
				const reg = /^[1-9][0-9]{0,3}$/
				if (num === undefined) {
					Alert(t('请设置轮询次数'))
					return false
				} else if (!reg.test(num + '')) {
					Alert(t('轮询次数范围：1次~9999次'))
					return false
				}
			}

			return flag
		},
	}))
)
